<template>
  <el-dialog
    v-model="props.folderDialog"
    :title="props.folderForm?.title"
    width="30%"
    :show-close="false"
    class="folderAdd"
  >
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      class="demo-ruleForm"
      :size="formSize"
      status-icon
    >
      <el-form-item
        label="文件上传"
        prop="fileUrl"
        v-if="props.folderForm?.id == ''"
      >
        <el-upload
          v-model:file-list="fileList"
          class="upload-demo"
          ref="upload"
          :auto-upload="true"
          :action="`${proxy.$http}/user/upload/uploadFile`"
          :show-file-list="true"
          :http-request="(resp: any) => { return handleUpload(resp) }"
          :before-upload="(resp: any) => { return fileBeforeUpload(resp) }"
          :on-progress="(resp: any) => { return fileProgress(resp) }"
          :on-error="(resp: any) => { return fileError(resp) }"
          :on-exceed="handleExceed"
          :on-remove="handleRemove"
          :headers="headers"
          limit="1"
          accept=".xlsx,.xls,.pdf,.doc,.docx,.ppt,.pptx"
        >
          <el-button type="primary">
            <svg
              t="1678678252428"
              class="icon"
              viewBox="0 0 1024 1024"
              version="1.1"
              xmlns="http://www.w3.org/2000/svg"
              p-id="3568"
              width="20"
              height="20"
            >
              <path
                d="M122.88 512s0 4.096-4.096 4.096v16.384s0 4.096 4.096 4.096l4.096 4.096 4.096 4.096s4.096 0 4.096 4.096h16.384s4.096 0 4.096-4.096l4.096-4.096 380.928-380.928c12.288-12.288 24.576-20.48 36.864-24.576 12.288-4.096 28.672-8.192 45.056-8.192 16.384 0 28.672 4.096 45.056 8.192 16.384 4.096 28.672 12.288 36.864 24.576 12.288 12.288 20.48 24.576 24.576 36.864 4.096 12.288 8.192 28.672 8.192 45.056 0 16.384-4.096 28.672-8.192 45.056-4.096 16.384-12.288 28.672-24.576 36.864L438.272 614.4l-4.096 4.096s0 4.096-4.096 4.096v16.384s0 4.096 4.096 4.096l4.096 4.096 4.096 4.096s4.096 0 4.096 4.096h16.384s4.096 0 4.096-4.096l4.096-4.096L749.568 368.64c16.384-16.384 28.672-36.864 36.864-57.344 8.192-20.48 12.288-45.056 12.288-69.632s8.192-36.864 0-57.344c-8.192-20.48-20.48-40.96-36.864-57.344s-36.864-28.672-57.344-36.864-45.056-12.288-69.632-12.288c-24.576 0-45.056 4.096-69.632 12.288-20.48 8.192-40.96 20.48-57.344 36.864l-380.928 380.928c-4.096 0-4.096 4.096-4.096 4.096z"
                fill="#ffffff"
                p-id="3569"
              ></path>
              <path
                d="M401.408 847.872c-12.288 4.096-28.672 8.192-45.056 8.192-16.384 0-28.672-4.096-45.056-8.192-12.288-8.192-24.576-16.384-36.864-28.672-12.288-12.288-20.48-24.576-24.576-36.864-4.096-12.288-8.192-28.672-8.192-45.056 0-16.384 4.096-28.672 8.192-45.056 4.096-16.384 12.288-28.672 24.576-36.864l311.296-311.296 4.096-4.096s0-4.096 4.096-4.096v-4.096V327.68v-4.096-4.096s0-4.096-4.096-4.096l-4.096-4.096-4.096-4.096s-4.096 0-4.096-4.096H573.44h-4.096-4.096-4.096s-4.096 0-4.096 4.096l-4.096 4.096L229.376 614.4c-16.384 16.384-28.672 36.864-36.864 57.344-8.192 20.48-12.288 45.056-12.288 69.632 0 24.576 4.096 45.056 12.288 69.632 8.192 20.48 20.48 40.96 36.864 57.344 16.384 12.288 36.864 24.576 57.344 32.768 20.48 8.192 45.056 12.288 69.632 12.288s45.056-4.096 69.632-12.288c20.48-8.192 40.96-20.48 57.344-36.864l380.928-380.928 4.096-4.096s0-4.096 4.096-4.096v-4.096-4.096-4.096-4.096s0-4.096-4.096-4.096l-4.096-4.096-4.096-4.096s-4.096 0-4.096-4.096h-4.096-4.096-4.096-4.096s-4.096 0-4.096 4.096l-4.096 4.096-393.216 368.64c-12.288 12.288-24.576 20.48-36.864 28.672z"
                fill="#ffffff"
                p-id="3570"
              ></path>
            </svg>
            上传文件
          </el-button>
        </el-upload>
      </el-form-item>
      <el-form-item label="文件名称" prop="fileName">
        <el-input
          v-model="ruleForm.fileName"
          placeholder="请输入文件名称"
          show-word-limit
          maxlength="128"
        />
      </el-form-item>
      <el-form-item label="文件类型" prop="fileType">
        <el-select
          v-model="ruleForm.fileType"
          class="m-2"
          placeholder="请选择文件类型"
          @change="fileTypeChange"
        >
          <el-option
            v-for="item in fileTypeList"
            :key="item.id"
            :label="item.configValue"
            :value="item.id"
          />
        </el-select>
        <el-button
          type="primary"
          plain
          style="margin-left: 10px"
          @click="addFileType()"
          >添加类型</el-button
        >
      </el-form-item>
      <el-form-item
        label="版本号"
        prop="versionNum"
        v-if="props.folderForm?.id == ''"
      >
        <el-input
          v-model="ruleForm.versionNum"
          placeholder="请输入当前文件版本号,比如:V0.1"
        />
      </el-form-item>
      <el-form-item label="设备类型" prop="deviceType">
        <el-cascader
          ref="cascaderRef"
          :show-all-levels="false"
          placeholder="请选择设备类型"
          v-model="ruleForm.deviceType"
          :props="cascaderProps"
          :options="deviceTypes"
        />
      </el-form-item>
      <el-form-item label="用途" prop="purpose">
        <el-input
          type="textarea"
          v-model="ruleForm.purpose"
          placeholder="请输入主要使用范围"
          maxlength="128"
          show-word-limit
        />
      </el-form-item>
      <div style="text-align: right">
        <el-button @click="quxiao(ruleFormRef)"> 取消 </el-button>
        <el-button
          type="primary"
          @click="queren(ruleFormRef)"
          :loading="loading"
          >确认</el-button
        >
      </div>
    </el-form>
    <AddFileType
      :fileTypeDialog="fileTypeDialog"
      :typeString="typeString"
      @submitFileType="submitFileType"
    ></AddFileType>
  </el-dialog>
</template>
<script setup lang="ts">
import {
  ElLoading,
  ElMessage,
  UploadProps,
  FormInstance,
  FormRules,
  UploadInstance
} from 'element-plus'
import {
  ref,
  reactive,
  watch,
  getCurrentInstance,
  defineAsyncComponent
} from 'vue'
import {
  addKnowledgeApi,
  editKnowledgeApi,
  getLastVersionByDirIdApi
} from '/@/api/knowledge'
import { dictionaryList, uploadFileApi } from '/@/api/publicApi'
import { Session } from '/@/utils/storage'
const AddFileType = defineAsyncComponent(() => import('./AddFileType.vue'))
const { proxy } = getCurrentInstance() as any
const props = defineProps({
  folderDialog: Boolean,
  folderForm: Object
})
const emit = defineEmits(['cancelFolder', 'submitFolder'])
const formSize = ref('default')
const loading = ref(false)
const ruleFormRef = ref<FormInstance>()
const cascaderRef = ref<any>(null)
const ruleForm = ref<any>({
  knowledgeLibraryId: '',
  fileType: '',
  fileTypeName: '',
  deviceType: '',
  fileName: '',
  fileUrl: '',
  fileSize: '',
  versionNum: '',
  purpose: ''
})

const cascaderProps = {
  expandTrigger: 'click' as const,
  value: 'id',
  label: 'configValue',
  emitPath: false,
  checkStrictly: true
}

const validateUrl = (rule: any, value: any, callback: any) => {
  if (ruleForm.value.fileUrl == '') {
    callback(new Error('请上传文件'))
  } else {
    callback()
  }
}
const rules = reactive<FormRules>({
  fileName: [{ required: true, message: '请输入文件名称', trigger: 'blur' }],
  fileUrl: [
    // { required: true, validator: validateUrl, trigger: 'blur' },
    { required: true, message: '请上传文件', trigger: 'blur' }
  ],
  versionNum: [{ required: true, message: '请输入版本号', trigger: 'blur' }],
  fileType: [{ required: true, message: '请选择文件类型', trigger: 'change' }]
})

const fileTypeList = ref<any>([])
const deviceTypes = ref<any>([])
const getFileTypeList = (val: any) => {
  dictionaryList({ configType: 'file_type', keyword: '' }).then((res) => {
    if (res.code == 0) {
      fileTypeList.value = res.data
      if (val) {
        fileTypeList.value.forEach((e: any) => {
          if (e.configValue == val) {
            ruleForm.value.fileType = e.id
            ruleForm.value.fileTypeName = e.configValue
          }
        })
      }
    }
  })
  dictionaryList({ configType: 'device_type', keyword: '' }).then((res) => {
    if (res.code == 0) {
      deviceTypes.value = res.data
    }
  })
}
getFileTypeList('')
const quxiao = (formEl: FormInstance | undefined) => {
  ruleForm.value.fileUrl = ''
  if (!formEl) return
  formEl.resetFields()
  emit('cancelFolder', props.folderForm?.zskId)
}
const queren = (formEl: FormInstance | undefined) => {
  loading.value = true
  if (!formEl) return
  formEl.validate((valid, fields) => {
    if (valid) {
      ruleForm.value.knowledgeLibraryId = props.folderForm?.zskId
      if (props.folderForm?.id != '') {
        let params = {
          id: props.folderForm?.form.id,
          fileType: ruleForm.value.fileType,
          fileTypeName: ruleForm.value.fileTypeName,
          deviceType: ruleForm.value.deviceType,
          dirName: ruleForm.value.fileName,
          purpose: ruleForm.value.purpose
        }
        editKnowledgeApi(params).then((res) => {
          if (res.code == 0) {
            ElMessage.success('编辑成功')
            ruleForm.value.fileUrl = ''
            emit('submitFolder', props.folderForm?.zskId)
            loading.value = false
          } else {
            ElMessage.warning(res.msg)
            loading.value = false
          }
        })
      } else {
        addKnowledgeApi(ruleForm.value).then((res) => {
          if (res.code == 0) {
            ElMessage.success('新增成功')
            ruleForm.value.fileUrl = ''
            emit('submitFolder', props.folderForm?.zskId)
            loading.value = false
          } else {
            ElMessage.warning(res.msg)
            loading.value = false
          }
        })
      }
    } else {
      loading.value = false
    }
  })
}

//文件上传
const fileList = ref<any>([])
const userInfo = Session.get('token')
const upload = ref<UploadInstance>()
const token = userInfo ? userInfo : ''
const headers = ref({
  'Content-Type': 'multipart/form-data',
  'Api-User-Token': token
})
const handleUpload = (file: any) => {
  const loading = ElLoading.service({
    lock: true,
    text: '上传中',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  uploadFileApi({ type: 11, file: file.file }).then((res) => {
    ruleForm.value.fileName = res.data.fileNames[0]
    ruleForm.value.fileUrl = res.data.fileIds[0]
    ruleForm.value.fileSize = res.data.fileSizes[0]
    ElMessage.success('文件上传成功！')
    loading.close()
  })
}

const fileProgress = (file: any) => {
  // if()
}

const fileError = (err: any) => {
  ElMessage.error('项目文件上传失败！')
  // eqForm.value.devicePicture = ''
}
const fileBeforeUpload = (rawFile: any) => {
  if (rawFile.size == 0) {
    ElMessage.warning('上传的文件是空文件，请重新上传！')
    return false
  }
}

const handleExceed: UploadProps['onExceed'] = (
  rawFile: any,
  uploadFiles: any
) => {
  if (fileList.value.length > 0) {
    ElMessage.warning('请先删除已有文件！')
    return
  }
}

const handleRemove = () => {
  ruleForm.value.fileName = ''
}

const fileTypeChange = (val: any) => {
  fileTypeList.value.forEach((item: any) => {
    if (item.id == val) {
      ruleForm.value.fileTypeName = item.configValue
    }
  })
}

const fileTypeDialog = ref(false)
const typeString = ref('file_type')
const addFileType = () => {
  fileTypeDialog.value = !fileTypeDialog.value
}

//添加类型回调
const submitFileType = (val: any) => {
  getFileTypeList(val)
  fileTypeDialog.value = !fileTypeDialog.value
}

watch(
  () => props.folderDialog,
  () => {
    if (props.folderForm?.id != '') {
      let obj = JSON.parse(JSON.stringify(props.folderForm?.form))
      if (obj.knowledgeList.length > 0) {
        ruleForm.value.fileUrl = obj.knowledgeList[0].fileUrl
        ruleForm.value.fileSize = obj.knowledgeList[0].fileSize
        ruleForm.value.versionNum = obj.knowledgeList[0].versionNum
      }
      ruleForm.value.fileName = obj.dirName
      ruleForm.value.purpose = obj.purpose
      ruleForm.value.fileType = obj.fileType
      ruleForm.value.fileTypeName = obj.fileTypeName
      ruleForm.value.deviceType = obj.deviceType
    } else {
      fileList.value = []
      ruleForm.value = {
        knowledgeLibraryId: '',
        fileType: '',
        fileTypeName: '',
        deviceType: '',
        fileName: '',
        fileUrl: '',
        fileSize: '',
        versionNum: '',
        purpose: ''
      }
    }
  }
)
</script>
<style scoped lang="scss">
.upload-demo {
  width: 100%;
}
</style>
<style>
.folderAdd .el-upload-list__item {
  width: 100% !important;
  height: auto !important;
}
</style>
